﻿/*----------------------------------------------------------------
// Copyright (C) 2011 
// 版权所有。 
//
// 文件名：AbstractThread.cs
// 文件功能描述：
//
// 
// 创建标识：kenter 2011-10-19
// EMAIL:kenter1643@163.com
//
// 修改标识：
// 修改描述：
//
// 修改标识：
// 修改描述：
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace WeiBOAPI.Threads
{
    public abstract class AbstractThread
    {
        protected Thread thread = null;
        protected CancellationTokenSource cts = new CancellationTokenSource();
        public bool SupperThread { get; set; }
        public int TimeSel { get; set; }

        public void threadRun()
        {
            while (true)
            {
                if (cts.Token.IsCancellationRequested) { break; }
                Run();
                Thread.Sleep(TimeSel);
            }
        }

        public abstract void Run();

        public void Start()
        {
            thread = new Thread(new ThreadStart(threadRun));
            thread.Start();
        }

        public abstract void ExStop(bool shutDown);

        public void Stop(bool shutDown)
        {
            ExStop(shutDown);
            if (thread != null)
            {
                cts.Cancel();
                try
                {
                    if (shutDown)
                    {
                        this.thread.Abort();
                    }
                }
                catch (ThreadAbortException) { }
                finally
                {
                    this.thread.Join();
                }
            }
        }
    }
}
